package mn.slide.laborberlin.refresh;

import java.net.URL;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import mn.slide.laborberlin.db.DatabaseManager;
import mn.slide.laborberlin.main.R;

import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class RefreshActivity extends Activity implements OnClickListener {
	private ListView listV;
	private String[] mStrings = {};
	private Button refresh_btn;
	private RelativeLayout transprent;
	private ProgressBar progressBar1, progressBar2;
	private TextView dismiss_txt;
	private UpdateClass updateClass;
	XMLReader xmlR;
	URL url;
	Document dom = null;
	boolean bkapitel, bLayoutTyp, bAnhang, bEintrag, bUntersuchung, bKuerzel,
			bName, bSynonym, bMaterialKuerzel, bMaterialName,
			bMaterialAbnahmemenge, bMaterial, bMethode, bKommentar,
			bBemerkungLV, bPreis, bDauer, bReferenzbereich, bEinheit, bAnhang1,
			bAllgemeines, bIndikation, bPraeanalytik, bBewertung,
			bDurchfuehrung, bKurzkommentar, bUeberschrift;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.home);
		listV = (ListView) findViewById(R.id.main_list);
		View footerView = ((LayoutInflater) this
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(
				R.layout.refresh, null, false);
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, mStrings);
		listV.addFooterView(footerView);
		listV.setAdapter(adapter);
		refresh_btn = (Button) footerView.findViewById(R.id.refresh_button);
		refresh_btn.setOnClickListener(this);
		transprent = (RelativeLayout) findViewById(R.id.transprent);
		progressBar1 = (ProgressBar) findViewById(R.id.progressBar1);
		progressBar2 = (ProgressBar) findViewById(R.id.progressBar2);
		progressBar2.setMax(100);
		dismiss_txt = (TextView) findViewById(R.id.dismiss_txt);
		dismiss_txt.setOnClickListener(this);
		try {

			/**
			 * Create a new instance of the SAX parser
			 **/
			SAXParserFactory saxPF = SAXParserFactory.newInstance();
			SAXParser saxP = saxPF.newSAXParser();
			xmlR = saxP.getXMLReader();

			url = new URL(
					"http://support.slide.mn/labor/Leistungsverzeichnis-Labor%20Berlin.xml");
			// URL
			// of
			// the
			// XML

			/**
			 * Create the Handler to handle each of the XML tags.
			 **/
			XMLHandler myXMLHandler = new XMLHandler();
			xmlR.setContentHandler(myXMLHandler);

		} catch (Exception e) {
			System.out.println(e);
		}

	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		getParent().findViewById(R.id.back_btn).setVisibility(View.INVISIBLE);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (refresh_btn == v) {
			transprent.setVisibility(View.VISIBLE);
			// downloadJsonStreamhistory(url);
			progressBar1.setVisibility(View.GONE);
			progressBar2.setVisibility(View.VISIBLE);
			updateClass = new UpdateClass();
			updateClass.execute();
		}
		if (dismiss_txt == v) {
			progressBar1.setVisibility(View.VISIBLE);
			progressBar2.setVisibility(View.GONE);
			transprent.setVisibility(View.GONE);
			if (updateClass != null) {
				updateClass.cancel(true);
			}
		}
	}

	private class UpdateClass extends AsyncTask<Void, Integer, Void> {

		@Override
		protected void onCancelled() {
			super.onCancelled();
			transprent.setVisibility(View.GONE);
			progressBar1.setVisibility(View.VISIBLE);
			progressBar2.setVisibility(View.GONE);
			progressBar2.setProgress(0);
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			progressBar2.setProgress(0);
		}

		@Override
		protected Void doInBackground(Void... params) {
			try {
				DatabaseManager.getInstance().upgradeDataBase();
				xmlR.parse(new InputSource(url.openStream()));
			} catch (Exception e) {

			}
			// try {
			//
			//
			// HttpClient httpclient = new DefaultHttpClient();
			// HttpGet httpget = new HttpGet(url);
			// HttpResponse response = httpclient.execute(httpget);
			// HttpEntity entity = response.getEntity();
			// Header[] clHeaders = response.getHeaders("Content-Length");
			// Header header = clHeaders[0];
			// int totalSize = Integer.parseInt(header.getValue());
			// Log.d("size", totalSize + "");
			// int downloadedSize = 0;
			// if (entity != null) {
			//
			// InputStream stream = entity.getContent();
			// XmlPullParserFactory factory = XmlPullParserFactory
			// .newInstance();
			// factory.setNamespaceAware(true);
			//
			// XmlPullParser xpp = factory.newPullParser();
			//
			// xpp.setInput(stream, "UTF-8");
			// int eventType = xpp.getEventType();
			// while (eventType != XmlPullParser.END_DOCUMENT) {
			// if (eventType == XmlPullParser.START_DOCUMENT) {
			// // System.out.println("Start document");
			// kapitel = new Kapitel();
			// ueberSchrift = new Ueberschrift();
			// } else if (eventType == XmlPullParser.START_TAG) {
			// if (xpp.getName().equals("Kapitel")) {
			// bkapitel = true;
			// kapitel.setValue(xpp.getAttributeValue(null,
			// "value"));
			// }
			// if (xpp.getName().equals("Ueberschrift")) {
			// ueberSchrift.setValue(xpp.getAttributeValue(
			// null, "value"));
			// }
			// if (xpp.getName().equals("Anhang")
			// && xpp.nextText().equals("Allgemeines")) {
			// bAnhang = true;
			// }
			// }
			//
			// else if (eventType == XmlPullParser.TEXT) {
			// if (bAnhang)
			// System.out.println(xpp.getText());
			// } else if (eventType == XmlPullParser.END_TAG) {
			// if (xpp.getName().equals("Kapitel")) {
			// bkapitel = false;
			// }
			// if (xpp.getName().equals("Ueberschrift")) {
			// bUeberschrift = false;
			// }
			// if (xpp.getName().equals("Anhang")) {
			// bAnhang = false;
			// }
			// }
			// eventType = xpp.next();
			// }
			// OutputStream output = new
			// FileOutputStream("/data/data/mn.slide.laborberlin.main/slide.xml");
			// byte buf[] = new byte[1024 * 1024];
			// int numBytesRead;
			// do
			// {
			// numBytesRead = stream.read(buf);
			// if (numBytesRead > 0)
			// {
			// downloadedSize += numBytesRead;
			// publishProgress((int) ((downloadedSize * 100) /
			// totalSize));
			// output.write(buf, 0, numBytesRead);
			// }
			// }
			// while (numBytesRead > 0);

			// httpclient.getConnectionManager().shutdown();
			// stream.close();
			// }
			// } catch (Exception e) {
			// e.printStackTrace();
			// }
			return null;
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			super.onProgressUpdate(values);
			progressBar2.setProgress(values[0]);
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			transprent.setVisibility(View.GONE);
			progressBar1.setVisibility(View.VISIBLE);
			progressBar2.setVisibility(View.GONE);
		}

	}
}